/* 
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

Project: MyMANET - A Platform to Build Customized MANET's
Developers: Ashwin Paranjpe, Santosh Vempala
Georgia Institute of Technology, Atlanta, USA
*/

#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

#define BUFFER_LEN 512
#define NUM_OF_PACKETS 40
#define PORT 9930


#define BUFFER 1024
#define NAM_LEN 1034 

int main(int argc, char **argv)
{
	struct sockaddr_in si_other;
	int s, i, slen=sizeof(si_other), flag=0;
	char buf[BUFFER_LEN];
	char msg[40];
	FILE *fp;
	char file_data[BUFFER];
	char node_name[NAM_LEN];
	char value;
	char addr_str[30];
	memset(addr_str, '\0', 30);
	memset(file_data, '\0', BUFFER_LEN);
	memset(node_name, '\0', BUFFER_LEN);
     
	if(argc != 2){
		printf("\nUsage: ./client [SERVER_IP]\n");
		exit(1);
	}	

	if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1){
		perror("socket");
		exit(1);
    	}

	memset((char *) &si_other, 0, sizeof(si_other));
	si_other.sin_family = AF_INET;
	si_other.sin_port = htons(PORT);

	sprintf( addr_str, "192.168.0.%s",argv[1] );
	if ((inet_aton(addr_str, &si_other.sin_addr)) == 0) {
		fprintf(stderr, "inet_aton() failed\n");
		exit(1);
	}
	
	fp = fopen("config/node_name_setup.conf", "r");
	if(fp==NULL){
		printf("\nCould not find node names\n");
		exit(1);
	}
#if 1
	while( (!feof(fp)))
	{
		fscanf(fp, "%c", &value);
		if (flag==0)
		{
			if (value==' ')
			{
				flag = 1;
			}

		}
		else if (flag==1)
		{
			if (value==' ' || value=='\0' || value=='\t' || value=='\n')
			{
				break;
			}
			file_data[i] = value;
			i++;
			flag = 1;
		}
	}

	strcpy(node_name, file_data);
	fclose(fp);

#endif
	//strcat (node_name, ": ");
	printf("Hi %s\n", node_name);

	for (i = 0; i < NUM_OF_PACKETS; i++) {
		printf("Enter the message you want to send: ");
		gets(msg);
		sprintf(buf, "%s:  %s\n", node_name, msg);

		if (sendto(s, buf, BUFFER_LEN, 0, (struct sockaddr *)&si_other, slen)==-1){
			perror("sendto()");
			exit(1);
		}
	}

	close(s);
	return 0;
}

